//职员管理

import React, {Component} from 'react';
import app from '../app';
import {Form, Input, Button, Table, Modal, Row, Upload, Icon, DatePicker, Select, Pagination, TreeSelect} from 'antd';
import {project, goods, type} from '../value';
import '../css/other.css';
import '../css/userManage.css';
import moment from 'moment';
import {config} from "../config";
import {AddSuppliers, EditSuppliers} from '../components/operateManage';

const SHOW_PARENT = TreeSelect.SHOW_PARENT;


const FormItem = Form.Item;
const confirm = Modal.confirm;
const RangePicker = DatePicker.RangePicker;
const Option = Select.Option;
const loopType = (type, data) => {
    let typeList = [];
    data.map((item, index) => {
        if (type.type_id === item.type_parentId) {
            item.label = item.type_name;
            item.value = item.type_id;
            item.key = item.type_id;
            typeList.push(item);
            type.children = typeList;
            loopType(item, data);
        } else {

        }
    })
};

class GoodsManage extends Component {
    constructor(props) {
        super(props);
        this.state = {
            visible: false,
            searchData: {},
            pagination: {current: 1, pageSize: 10, total: 0},
            positionId: [],
            data: [],
            type: 0,
            optionValue: [
                {
                    id: '01',
                    name: '肉食'
                },
                {
                    id: '02',
                    name: '素食'
                }
            ]
        }
    }

    columns = [
        {
            title: '序号',
            dataIndex: 'order_number'
        },
        {
            title: '商品图片',
            dataIndex: 'file_path',
            render: file_path => {
                return (
                    <img src={config.imgServerUrl + file_path} style={{width: '70px', height: '70px'}}/>
                )
            }
        },
        {
            title: '商品编号',
            dataIndex: 'goods_code'
        },
        {
            title: '商品名称',
            dataIndex: 'goods_name'
        },
        {
            title: '价格',
            dataIndex: 'goods_price'
        },
        {
            title: '成本',
            dataIndex: 'goods_cost'
        },
        {
            title: '分类',
            dataIndex: 'goods_type'
        },
        {
            title: '库存',
            dataIndex: 'goods_stock'
        },
        {
            title: '操作',
            dataIndex: this.columns,
            render: data => {
                return (
                    <div>
                        <Button onClick={() => this.handleRedirectDetail(data.goods_id)} type={'primary'}>编辑</Button>
                        {
                            data.goods_isable === '1' ? <Button style={{marginLeft: '10px'}} type="danger"
                                                                onClick={() => this.handleEditStatus(data.goods_id, 0)}>下架</Button> :
                                <Button style={{marginLeft: '10px'}} type="primary"
                                        onClick={() => this.handleEditStatus(data.goods_id, 1)}>上架</Button>
                        }
                        <Button style={{marginLeft: '10px'}} type="danger"
                                onClick={() => this.handleEditStatus(data.goods_id, 2)}>删除</Button>
                    </div>
                )
            }
        },
    ];
    formItemLayout = {
        labelCol: {span: 8},
        wrapperCol: {span: 12},
    };

    render() {
        const rowSelection = {
            // 表格中复选框发生变化时
            onChange: (selectedRowKeys, selectedRows) => {
                let positionId = [];
                let positionName = [];
                positionId = selectedRowKeys;
                selectedRows.forEach((item) => {
                    positionName.push(item.role_name);
                });
                this.setState({
                    positionId: positionId,  //批量选中的职位ID
                    positionName: positionName,
                    selectCount: selectedRowKeys.length, //一共选择的职位数量
                })
            },

        };
        const {getFieldDecorator} = this.props.form;
        return (
            <div style={{paddingBottom: 25}}>
                <div className="pageTitle">
                    商品管理
                </div>
                <SearchLists refresh={() => this.handleRefreshAfterCreate()}
                             clickSearch={(values) => this.handleGetValue(values)}/>

                <div className={'btnContainer'} style={{display: 'flex'}}>
                    <div style={{width: '20%'}}>
                        <Button type={'primary'} onClick={() => this.handleRedirectGoodsAdd()}>新增商品</Button>
                    </div>
                    <div style={{width: '80%', textAlign: 'right'}}>
                        <Button type={'primary'} onClick={() => this.handleEditAll(2)}>批量删除</Button>
                        <Button type={'primary'} onClick={() => this.handleEditAll(1)}>批量上架</Button>
                        <Button type={'primary'} onClick={() => this.handleEditAll(0)}>批量下架</Button>
                        {/*<Button type={'primary'} onClick={() => this.handleEdit(1)}>批量修改库存</Button>*/}
                        {/*<Button type={'primary'} onClick={() => this.handleEdit(2)}>批量修改分类</Button>*/}
                        {/*<Button type={'primary'} onClick={() => this.handleEdit(3)}>批量修改价格</Button>*/}
                    </div>
                </div>
                <Row style={{marginTop: '20px'}}>
                    <Table
                        rowSelection={rowSelection}
                        columns={this.columns}
                        rowKey={(record, index) => record.goods_id}
                        dataSource={this.state.data}
                        loading={this.state.loading}
                        pagination={false}
                        onChange={this.handleTableChange}
                    />
                </Row>
                <Row style={{textAlign: 'right', marginTop: 20}}>
                    <Pagination {...this.state.pagination} showSizeChanger showQuickJumper
                                onChange={(page, pageSize) => this.handleOnChange(page, pageSize)}
                                onShowSizeChange={(current, size) => this.handleOnShowSizeChange(current, size)}/>
                </Row>

                <Modal visible={this.state.visible}
                       maskClosable={false}
                       title="修改"
                       okText={"提交"}
                       width={'500px'}
                       cancelText={"返回"}
                       onCancel={() => this.showModal(false)}
                       footer={
                           <div>
                               <Button type={'primary'} onClick={() => this.handleSave()}>保存</Button>
                           </div>
                       }
                >
                    {
                        this.state.type === 1 ?
                            <FormItem label={"库存"} style={{display: 'flex'}} {...this.formItemLayout}>
                                {getFieldDecorator('stock', {
                                    rules: [{required: true, message: '请输入库存'}],
                                })(
                                    <Input
                                        placeholder="请输入库存" style={{width: '200px'}} type={'number'}/>
                                )}
                            </FormItem> : ''
                    }
                    {
                        this.state.type === 2 ?
                            <FormItem label={"分类"} style={{display: 'flex'}} {...this.formItemLayout}>
                                {getFieldDecorator('sku_name', {
                                    rules: [{required: true, message: '请选择分类'}],
                                })(
                                    <Select placeholder="请选择分类" style={{width: '200px'}}>
                                        {
                                            this.state.optionValue.map((item, index) => {
                                                return (
                                                    <Option value={item.id} key={index}>{item.name}</Option>
                                                )
                                            })
                                        }
                                    </Select>
                                )}
                            </FormItem> : ''
                    }
                    {
                        this.state.type === 3 ?
                            <FormItem label={"价格"} style={{display: 'flex'}} {...this.formItemLayout}>
                                {getFieldDecorator('price', {
                                    rules: [{required: true, message: '请输入价格'}],
                                })(
                                    <Input
                                        placeholder="请输入价格" style={{width: '200px'}} type={'number'}/>
                                )}
                            </FormItem> : ''
                    }
                </Modal>
            </div>
        )
    }

    /**
     * 初始化
     */
    componentDidMount() {
        const param = {
            page: 1,
            size: 10,
            type: 1
        };
        this.searchGoodsList(param);
    }

    /**
     * 显示隐藏弹框
     * @param visible
     */
    showModal(visible) {
        this.setState({visible});
    }

    /**
     * 批量修改
     * @param type
     */
    handleEdit(type) {
        let positionId = this.state.positionId;
        if (!positionId || positionId.length <= 0) {
            app.alert('请选择商品');
            return;
        }
        this.setState({type});
        this.showModal(true);
    }

    /**
     * 获取搜索条件
     */
    handleGetValue(value) {
        this.setState({searchData: value});
        const param = {
            page: 1,
            size: 10,
            type: 1,
            ...value
        };
        this.searchGoodsList(param);
    }

    /**
     * 处理创建后刷新事件
     */
    handleRefreshAfterCreate() {
        const param = {};
        this.searchProject(param);
    }

    /**
     * 处理删除后刷新事件
     */
    handleRefreshAfterDelete() {
        const {searchData} = this.state;
        const param = {
            page: 1,
            size: 10,
            type: 1,
            ...searchData
        };
        this.searchGoodsList(param);
    }

    /**
     * 处理更新后刷新事件
     */
    handleRefreshAfterUpdate() {
        const {searchData, pagination} = this.state;
        const param = {
            page: pagination.current,
            size: pagination.size,
            type: 1,
            ...searchData
        };
        this.searchGoodsList(param);
    }

    /**
     * 处理页码、显示数量变化事件
     * @param pagination
     * @param filters
     * @param sorter
     */
    handleTableChange = (pagination, filters, sorter) => {
        const current = pagination.current;
        const size = pagination.pageSize;
        const pagination1 = this.state.pagination;
        pagination1.current = current;
        pagination1.pageSize = size;
        this.setState({pagination: pagination1});
    };

    /**
     * 处理页面改变事件
     * @param page
     * @param pageSize
     */
    handleOnChange(page, pageSize) {
        const {searchData} = this.state;
        const param = {
            page,
            size: pageSize,
            type: 1,
            ...searchData
        };
        this.searchGoodsList(param);
    }

    /**
     * 处理pageSize变化回调
     * @param current
     * @param size
     */
    handleOnShowSizeChange(current, size) {
        const {searchData} = this.state;
        const param = {
            page: current,
            size,
            type: 1,
            ...searchData
        };
        this.searchGoodsList(param);
    }

    /**
     * 查找商品列表
     * @param param
     */
    searchGoodsList(param) {
        let _this = this;
        _this.setState({loading: true});
        app.post(goods.SEARCH_GOODS_LIST, param).then(result => {
            if (result.code === 1) {
                const data = result.data;
                for (let i = 0; i < data.length; i++) {
                    data[i].order_number = i + 1;
                }
                const pagination = {total: data.length, current: param.page, pageSize: param.size};
                this.setState({pagination, data: data, loading: false});
            } else {
                app.alert(result.msg, 'info', 1);
                const pagination = {total: 0, current: 0, pageSize: 0};
                this.setState({pagination, data: [], loading: false});
            }
        });
    }

    /**
     * 操作用户状态
     */
    handleEditStatus(id, type) {
        const _this = this;
        const goodsList = [{goods_id: id}];
        const param = {
            goodsList,
            goods_isable: type.toString()
        };
        if (type === 2) {
            confirm({
                content: '您确定要删除该商品吗？',
                onOk() {
                    app.post(goods.UPDATE_GOODS_LIST_ISABLE, param).then((req) => {
                        if (req.code === 1) {
                            app.alert("删除成功", 'success', 1);
                            _this.handleRefreshAfterDelete();
                        } else {
                            app.alert(req.msg, 'info', 1);
                        }
                    })
                },
                onCancel() {
                },
            });
        } else if (type === 0) {
            confirm({
                content: '您确定要下架该商品吗？',
                onOk() {
                    app.post(goods.UPDATE_GOODS_LIST_ISABLE, param).then((req) => {
                        if (req.code === 1) {
                            app.alert("下架成功", 'success', 1);
                            _this.handleRefreshAfterDelete();
                        } else {
                            app.alert(req.msg, 'info', 1);
                        }
                    })
                },
                onCancel() {
                },
            });
        } else if (type === 1) {
            app.post(goods.UPDATE_GOODS_LIST_ISABLE, param).then((req) => {
                if (req.code === 1) {
                    app.alert("上架成功", 'success', 1);
                    _this.handleRefreshAfterDelete();
                } else {
                    app.alert(req.msg, 'info', 1);
                }
            })
        }
    }

    /**
     * 跳转详情页
     */
    handleRedirectDetail(goods_id) {
        this.props.history.push(config.path + '/home/goodsEdit/' + goods_id);
    }

    /**
     * 跳转到新增页
     */
    handleRedirectGoodsAdd(){
        this.props.history.push(config.path + '/home/goodsAdd');
    }

    /**
     * 批量编辑商品
     */
    handleEditAll(type) {
        const _this = this;
        let positionId = this.state.positionId;
        if (positionId.length <= 0) {
            app.alert('请选择商品');
            return;
        }
        let goodsList = [];
        for (let i = 0; i < positionId.length; i++) {
            let item = {
                goods_id: positionId[i]
            };
            goodsList.push(item);
        }
        const param = {
            goods_isable: type.toString(),
            goodsList
        };
        let text = '';
        switch (type) {
            case 0:
                text = '下架成功';
                break;
            case 1:
                text = '上架成功';
                break;
            case 2:
                text = '删除成功';
                break;
        }
        app.post(goods.UPDATE_GOODS_LIST_ISABLE, param).then((req) => {
            if (req.code === 1) {
                app.alert(text, 'success', 1);
                _this.handleRefreshAfterDelete();
            } else {
                app.alert(req.msg, 'info', 1);
            }
        });
        console.log(positionId);
    }

    /**
     * 保存
     */
    handleSave() {
        const _this = this;
        let {type, positionId} = this.state;
        app.post(project.DELETE_PROJECT, {}).then((req) => {
            if (req.code == '1') {
                app.alert("删除成功", 'success', 2);
                _this.handleRefreshAfterDelete();
            } else {
                app.alert(req.msg, 'error', 2);
            }
        })
    }
}


class SearchList extends Component {
    constructor(props) {
        super(props);
        this.state = {
            project_name: '',
            optionValue: [
                {
                    id: '01',
                    name: '会员注册奖励'
                }
            ],
            shopType: [],
        }
    };

    render() {
        return (
            <div className={'user-search-container'}>
                <div className={'user-search-item1'}>
                    <div className={'user-search-item-type'}>商品编号：</div>
                    <Input placeholder={'商品编号'} style={{width: 180}}
                           onChange={(e) => this.handleUserNameChange(e)}
                           onPressEnter={(e) => this.handleUserNamePress(e)}/>
                </div>
                <div className={'user-search-item1'} style={{marginLeft: 10}}>
                    <div className={'user-search-item-phone'}>商品名称：</div>
                    <Input placeholder={'商品名称'} style={{width: 150}}
                           onChange={(e) => this.handleContactChange(e)}
                           onPressEnter={(e) => this.handleContactPress(e)}/>
                </div>
                <div className={'user-search-item1'} style={{marginLeft: 10}}>
                    <div className={'user-search-item-status'}>商品分类：</div>
                    <TreeSelect
                        treeData={this.state.shopType}
                        treeCheckable={true}
                        multiple={true}
                        onSelect={this.getShopType}
                        showCheckedStrategy={SHOW_PARENT}
                        searchPlaceholder='请选择'
                        style={{width: 150}}
                    />
                </div>
                <div className={'user-search-footer'}>
                    <Button type="primary" onClick={() => this.handleSearchComplain()}>搜索</Button>
                    {/*<AddInvitationActivitys refresh={() => this.handleRefreshAfterCreate()}></AddInvitationActivitys>*/}
                </div>
            </div>
        )
    };

    componentDidMount() {
        this.requestShopType();
    };

    /**
     * 处理用户名输入框变化事件
     * @param e
     */
    handleUserNameChange(e) {
        this.setState({goods_code: e.target.value});
    }

    /**
     * 处理种类状态框变化事件
     * @param e
     */
    handleContactChange(e) {
        this.setState({goods_name: e.target.value});
    }

    handleUserNamePress(e) {
        this.handleSearchComplain1({key: 'goods_code', value: e.target.value});
    }

    handleContactPress(e) {
        this.handleSearchComplain1({key: 'goods_name', value: e.target.value});
    }

    /**
     * 获取搜索条件
     */
    handleSearchComplain1(param) {
        let {goods_name, goods_code, typeSearch} = this.state;
        if (param.key === 'goods_code') {
            goods_code = param.value;
        }
        if (param.key === 'goods_name') {
            goods_name = param.value;
        }
        if (param.key === 'typeSearch') {
            typeSearch = param.value;
        }
        let data = {
            codeSearch: goods_code,
            nameSearch: goods_name,
            typeSearch
        };
        this.props.clickSearch(data);
    };

    /**
     * 搜索
     */
    handleSearchComplain() {
        let {goods_name, goods_code, typeSearch} = this.state;
        let data = {
            codeSearch: goods_code,
            nameSearch: goods_name,
            typeSearch
        };
        this.props.clickSearch(data);
    }


    // 获取商家选中的分类
    getShopType = (value, label, extra) => {
        console.log(value, label, extra);
        let selectShopType = [];
        let temp = {};
        extra.checkedNodes.forEach((item) => {
            temp = {
                type_id: item.props.type_id,
                type_level: item.props.type_level,
                type_name: item.props.type_name,
                type_parentId: item.props.type_parentId
            };
            selectShopType.push(temp);
        });
        console.log(selectShopType);
        let typeSearch = '';
        for (let i = 0; i < selectShopType.length; i++) {
            typeSearch += selectShopType[i].type_id + ',';
        }
        typeSearch = typeSearch.substr(0, typeSearch.length - 1);
        this.setState({typeSearch: typeSearch});
        this.handleSearchComplain1({key: 'typeSearch', value: typeSearch});
    };

    /**
     * 获取分类
     */
    requestShopType() {
        let msg = {};
        let temp;
        app.post(type.SEARCH_ALL_TYPE, {}).then(req => {
            if (req.code == 1) {
                let firstMenu = [];
                req.data.map((item) => {
                    // 先查到最顶层数据
                    temp = {
                        label: item.type_name,
                        value: item.type_id,
                        type_id: item.type_id,
                        type_isable: item.type_isable,
                        type_level: item.type_level,
                        type_name: item.type_name,
                        type_parentId: item.type_parentId,
                        key: item.type_id
                    };
                    if (!item.type_parentId) {
                        firstMenu.push(temp);
                    }
                });
                firstMenu.map((item) => {
                    loopType(item, req.data);  //根据最顶层的数据所含的子数据的ID和所有的分类ID比较，相同的则为他的子数据
                });
                this.setState({shopType: firstMenu});
            } else if (req.msg == '查询无记录') {
                app.alert('请先添加分类', 'error', 3);
            } else if (req.code == 2) {
                app.alert(req.msg, 'error', 3)
            }
        });
    }
}

const SearchLists = Form.create()(SearchList);
const GoodsManages = Form.create()(GoodsManage);

export default GoodsManages;